package com.kcwl.carrier.application.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.kcwl.carrier.domain.entity.CarrierConfig;
import com.kcwl.carrier.domain.repository.ICarrierConfigRepository;
import com.kcwl.carrier.infrastructure.repository.po.CarrierConfigPO;
import com.kcwl.carrier.interfaces.command.CarrierConfigCommand;
import com.kcwl.carrier.interfaces.dto.CarrierConfigDTO;
import com.kcwl.ddd.interfaces.dto.PageInfoDTO;
import com.kcwl.ddd.interfaces.query.PageQuery;
import com.kcwl.framework.utils.CollectionUtil;
import com.kcwl.framework.utils.KcBeanConverter;
import com.kcwl.framework.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 刘旭超
 * @date 2022年12月05日 15:51
 * @Description
 */
@Slf4j
@Service
public class CarrierConfigApplicationService {

    @Autowired
    private ICarrierConfigRepository carrierConfigRepository;

    public PageInfoDTO<CarrierConfigDTO> queryCarrierConfigPageList(PageQuery query) {
        IPage<CarrierConfigPO> page = carrierConfigRepository.queryCarrierConfigPageList(query);
        log.info("用户配置查询：" + JSONObject.toJSONString(page));
        List<CarrierConfigPO> list = page.getRecords();
        if (CollectionUtil.isEmpty(list)) {
            list = new ArrayList<>();
        }
        return new PageInfoDTO<>(page.getTotal(), page.getCurrent(), page.getSize(), KcBeanConverter.toList(list, CarrierConfigDTO.class));
    }

    public void editCarrierConfig(CarrierConfigCommand command) {
        carrierConfigRepository.updateCarrierConfig(KcBeanConverter.toBean(command, CarrierConfig.class));
    }

    /**
     * 查询绑定车辆上限
     * @param id
     * @return
     */
    public Integer queryVehicleBingingLimit(Long id) {
        CarrierConfigPO carrierConfigPO = carrierConfigRepository.queryCarrierConfig(id);
        if (carrierConfigPO != null && StringUtil.isNotBlank(carrierConfigPO.getConfigValue())) {
            return Integer.parseInt(carrierConfigPO.getConfigValue());
        }
        return null;
    }
}
